/**
 * JAVACC DEMO 1.0
 */
package com.apache.portal.thread;

import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.database.constant.SpringContextLoader;
import com.apache.database.model.Page;
import com.apache.excp.ConfigConstant;
import com.apache.excp.core.impl.LoadManager;
import com.apache.excp.core.impl.exp.utils.ExcelExpTemplateUtil;
import com.apache.excp.core.manager.ExportExecl;
import com.apache.excp.core.model.ExportVo;
import com.apache.portal.common.oscache.CacheHelper;
import com.apache.portal.common.util.PortalPubFactory;
import com.apache.rpc.common.LoadRpcService;
import com.apache.tools.ConfigUtil;
import com.apache.tools.DataMap;
import com.apache.tools.StrUtil;
import com.apache.uct.common.LoginUser;
import com.apache.uct.common.ToolsUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.swing.text.html.parser.Entity;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * description: 创建导出模板任务线程类
 *
 * @author fpc 创建时间：2018-9-18
 */
public class TemplatesOutTask implements Callable<Integer> {

//    ProxyManager iusProxyManager = (ProxyManager) SpringContextLoader.getBean("iusProxyManager");
    private String filePath;

    private Map<String, String> params;


    private LoginUser loginUser;


    public TemplatesOutTask( String filePath ,Map<String, String> params, LoginUser loginUser) {
        this.filePath = filePath;
        this.params = params;
        this.loginUser = loginUser;
    }

    /**
     * TODO 简单描述该方法的实现功能（可选）.
     *
     * @see Callable#call()
     */
    public Integer call() throws Exception {
        getParams();
        String tempEname = params.get("smExpTemplates.tempEname");
        if (ConfigConstant.isNull(filePath)) {
            filePath = ConfigConstant.getClassLoaderPath() + "templates/";
            ConfigConstant.newCreateFolder(filePath);
        }
        int count = 1;
        try {
            boolean mark = true;
            String beanId = PortalPubFactory.getInstance().getBeanId(params.get("datasource"));
            do {
                Map map = this.params;
                ResultEntity entity = LoadRpcService.service()
                        .doServiceClient(beanId, "dymicSql", map,
                                PortalPubFactory.getInstance().getRpcInfo("ius"));
                if("T".equals(entity.getResult())){
                    mark = false;
                }
            } while (mark);
            String jsonArr = this.params.get("smExpTemplates.objColumn");
            JSONArray jsonArrays = JSONArray.fromObject(jsonArr);
            Map<String,Object> map = new HashMap<String,Object>();
            //[{"objName":"元器件表","objColumns":[{"key":"testInformation","value":"试验信息"},{"key":"compContent","value":"元器件内容"},{"key":"createTime","value":"创建时间"},{"key":"radiationResistanceIndex","value":"抗辐照指标"}]}]
            for (int i = 0; i<jsonArrays.size();i++)
            {
                JSONObject jsonObject = (JSONObject)jsonArrays.get(i);
                JSONArray jsonColumnsArray = (JSONArray)jsonObject.get("objColumns");
                String objNamestr = (String)jsonObject.get("objName");
                map.put(objNamestr,jsonColumnsArray);
            }
            OutputStream out = null;
            try {
                for (String key : map.keySet()) {
                    out = new FileOutputStream(filePath+tempEname);
                    ExcelExpTemplateUtil expTemplateUtil = new ExcelExpTemplateUtil();
                    expTemplateUtil.exportExcel(key,(List<JSONObject>) map.get(key),out);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return 0;
            }finally {
                if(out!=null){
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
        return count;
    }

    private void getParams() {
        String pageName = params.get("pageName");
        String formName = params.get("formName");
        String key = formName + "_" + pageName;
        params.remove("pageName");
        params.remove("formName");
        Map map = (Map) CacheHelper.getInstance()
                .getIusParamCache(key);
        if (ToolsUtil.isEmpty(map)) {
            return ;
        }
        String modelType = String.valueOf(map.get("modelTypes"));
        String datasource = String.valueOf(map.get("sysName"));
        if (modelType.startsWith("i_")) {
            params.put("objName", modelType.substring(2));
        } else if (modelType.startsWith("ib_")) {
            params.put("objName", modelType.substring(3));
        }
        String rules = String.valueOf(map.get("rulesName"));
        String evelName = String.valueOf(map.get("evelName"));//方法拦截方式
        params.put("sqlKeyId", "sqlKeyId");
        if (ToolsUtil.isNotNull(rules)) {
            params.put("sqlKeyId", rules);
            if (Validator.isNotNull(evelName)) {
                params.put(evelName, rules);
            } else {
                params.put("beforMethodKey", rules);
            }
        }
        params.put("resultType", "processSql");
        params.put("loginUser_userEname", loginUser.getUserEname());//确保其他表中没有该字段
        params.put("modelTypes", modelType);
        params.put("sysPass", ConfigUtil.getInstance().interfacePass());
        params.put("datasource", datasource);
    }

    public static void main(String[] args) {

    }
}
